package Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2024-01-24
 * Time: 18:10
 */
class Counter {
    private int count;
    public void add() {
        synchronized (this) {
            count++;
        }
    }
//    如果直接给方法加锁，相当于以this为锁对象
//    synchronized public void add() {
//        count++;
//    }

//    给static方法加锁的锁对象为类对象
    synchronized public static void test() {}
//    test1加锁方式的锁对象与test方法的一样
    public static void test1() {
        synchronized (Counter.class) {

        }
    }
    public int getCount() {
        return count;
    }
}
public class ThreadDemo5 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println(counter.getCount());
    }
}
